package top.healthylife.gateway.platform.bj.api.check;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.ContentType;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import top.healthylife.basics.utils.exception.BusinessException;
import top.healthylife.gateway.core.config.BaseConfig;
import top.healthylife.gateway.core.service.CheckSecretService;
import top.healthylife.gateway.platform.bj.api.config.SystemConfig;
import top.healthylife.gateway.platform.bj.api.util.BjHttpUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * @author : GaoZeXi
 * @date 2021/7/15 14:31
 */
@Service
@Slf4j
public class CheckSecretServiceImpl implements CheckSecretService {
    @Override
    public void checkSecret(BaseConfig baseConfig) {
        SystemConfig systemConfig = (SystemConfig) baseConfig;
        BjHttpUtil.EnvType env = systemConfig.getEnv();
        String merchantName = systemConfig.getMerchantName();
        String merchantPwd = systemConfig.getMerchantPwd();
        String encryptPwd = SecureUtil.md5(merchantPwd);

        String currentEnvLoginUrl = "";
        try {
            currentEnvLoginUrl = BjHttpUtil.getCurrentEnvLoginUrl(env);
            Map<String, Object> form = new HashMap<>(2);
            form.put("merchant_name", merchantName);
            form.put("merchant_pwd", encryptPwd);
            String body = HttpRequest.post(currentEnvLoginUrl).form(form).contentType(ContentType.FORM_URLENCODED.getValue()).execute().body();
            JSONObject jsonObject = JSONObject.parseObject(body);
            String key = jsonObject.get(BjHttpUtil.CODE).toString();
            if (!BjHttpUtil.SUCCESS.equals(key)) {
                if (BjHttpUtil.respCodeMap.containsKey(key)) {
                    throw new BusinessException(BjHttpUtil.respCodeMap.get(key));
                }else{
                    throw new BusinessException(jsonObject.getString(BjHttpUtil.MSG));
                }
            }
        } catch (Exception e) {
            log.error("登录冰鉴平台失败,账号:{}.密码:{},加密后密码:{},环境:{},登录url:{},错误原因:{}", merchantName, merchantPwd, encryptPwd, env, currentEnvLoginUrl,e.getMessage());
            throw new BusinessException(e.getMessage());
        }
    }
}
